#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include "util.h"

#ifndef QUERY_H
#define QUERY_H

void query_user_position(char* user, float* x, float* y, float* z) {
    char* root = getenv("RELAT_ROOT");

    char user_position_file_name[256];
    sprintf(user_position_file_name, "%s/%s/position", root, user);

    FILE* user_position_file;
    if ((user_position_file = fopen(user_position_file_name, "r")) == NULL) {
        perror("could not open user position file");
        exit(-1);
    }

    if (fscanf(user_position_file, "%f %f %f\n", x, y, z) != 3) {
        exit(-1);
    }

    fclose(user_position_file);
}

void query_unit_position(char* user, char* unit, float* x, float* y, float* z) {
    char* root = getenv("RELAT_ROOT");

    char unit_position_file_name[256];
    sprintf(unit_position_file_name, "%s/%s/%s/position", root, user, unit);

    FILE* unit_position_file;
    if ((unit_position_file = fopen(unit_position_file_name, "r")) == NULL) {
        perror("could not open unit position file");
        exit(-1);
    }

    char unit_move_file_name[256];
    sprintf(unit_move_file_name, "%s/%s/%s/move", root, user, unit);

    FILE* unit_move_file;
    if ((unit_move_file = fopen(unit_move_file_name, "r")) == NULL) {
        perror("could not open unit move file");
        exit(-1);
    }

    if (fscanf(unit_position_file, "%f %f %f\n", x, y, z) != 3) {
        exit(-1);
    }

    float dx, dy, dz;
    unsigned long from, to;
    if (fscanf(unit_move_file, "%ul %ul %f %f %f", &from, &to, &dx, &dy, &dz) != 5) {
        printf("awoo\n");
        exit(-1);
    }

    unsigned long current_time = get_unix_timestamp();
    float dt = ((current_time < to ? current_time : to) - from) / 1000.0;

    *x += dx * dt;
    *y += dy * dt;
    *z += dz * dt;

    fclose(unit_position_file);
    fclose(unit_move_file);
}

#endif
